<template>
<div>
    <!-- 面包屑 -->
 <el-breadcrumb separator-class="el-icon-arrow-right">
  <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
  <el-breadcrumb-item>用户管理</el-breadcrumb-item>
  <el-breadcrumb-item>用户列表</el-breadcrumb-item>
</el-breadcrumb>
<!-- 卡片 -->
<el-card class="box-card">
    <el-row  class="btns" :gutter="15">
        <el-col :span="7">
            <div>
                <el-input placeholder="请输入内容" class="input-with-select" v-model="querInfo.query">
                    <el-button slot="append" icon="el-icon-search" @click="getuserformData"></el-button>
                </el-input>
            </div>
        </el-col>
        <el-col :span="4">
            <el-button type="primary" @click="tjFormVisible = true">添加用户</el-button>
        </el-col>
    </el-row>
    <!-- 表单 -->
  <el-table
    :data="userformData"
    stripe
    style="width: 100%">
    <el-table-column type="index"></el-table-column>
    <el-table-column
      prop="username"
      label="姓名">
    </el-table-column>
    <el-table-column
      prop="email"
      label="邮箱">
    </el-table-column>
    <el-table-column
      prop="mobile"
      label="电话">
    </el-table-column>
    <el-table-column
      prop="role_name"
      label="角色">
    </el-table-column>
    <el-table-column
      label="状态">
      <template slot-scope="scope">
        <el-switch
        @change="changesj(scope.row)"
            v-model="scope.row.mg_state"
            active-color="#13ce66">
        </el-switch>
      </template>
    </el-table-column>
    <el-table-column
      label="操作"
      width="180">
        <template slot-scope="scope">
        <el-button type="primary" icon="el-icon-edit" size="mini" @click="bjForm(scope.row.id)"></el-button>
        <el-button type="danger" icon="el-icon-delete" size="mini" @click="delete1(scope.row.id)"></el-button>
        <el-tooltip class="item" effect="dark" content="分配角色" placement="top" enterable>
        <el-button type="warning" icon="el-icon-setting" size="mini"  @click="getjsForm(scope.row)"></el-button>
        </el-tooltip>
        </template>
    </el-table-column>
  </el-table>
  <!-- 分页 -->
   <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-change="querInfo.pagenume"
      :page-sizes="[1, 2, 4, 5]"
      :page-size="querInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
</el-card>

<!-- 编辑用户对话框 -->
<el-dialog title="编辑用户" :visible.sync="bjFormVisible" width="50%" @close="guanbi">
  <el-form label-width="80px"  :model="bianjiForm" :rules="ruless"  ref="editFormRef">
    <el-form-item label="用户名">
    <el-input  disabled  v-model="bianjiForm.username"></el-input>
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
    <el-input v-model="bianjiForm.email"></el-input>
    </el-form-item>
    <el-form-item label="手机" prop="mobile">
    <el-input v-model="bianjiForm.mobile"></el-input>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="guanbi">取 消</el-button>
    <el-button type="primary" @click="xiugaibtn(bianjiForm.id)">确 定</el-button>
  </div>
</el-dialog>

<!-- 添加用户对话框 -->
<el-dialog title="添加用户" :visible.sync="tjFormVisible" width="50%" @close="guanbi1">
  <el-form label-width="80px"  :model="tianjiaForm" :rules="ruless"  ref="editFormRef1">
    <el-form-item label="用户名" prop="username">
    <el-input v-model="tianjiaForm.username"></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="password">
    <el-input v-model="tianjiaForm.password"></el-input>
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
    <el-input v-model="tianjiaForm.email"></el-input>
    </el-form-item>
    <el-form-item label="手机" prop="mobile">
    <el-input v-model="tianjiaForm.mobile"></el-input>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="guanbi1">取 消</el-button>
    <el-button type="primary" @click="tianjiabtn">确 定</el-button>
  </div>
</el-dialog>

<!-- 分配角色对话框 -->
<el-dialog title="分配角色" :visible.sync="jsFormVisible" width="50%" @close="guanbi2">
  <el-form label-width="80px"  :model="jsForm" ref="jsFormRef1">
    <p>当前用户名：{{jsForm.username}}</p>
    <p>当前的角色：{{jsForm.role_name}}</p>
    <p>分配新角色：
    <el-select v-model="value1" placeholder="请选择">
    <el-option
      v-for="item in rolesList"
      :key="item.id"
      :label="item.roleName"
      :value="item.id">
    </el-option>
  </el-select></p>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="guanbi2">取 消</el-button>
    <el-button type="primary" @click="jsbtn()">确 定</el-button>
  </div>
</el-dialog>
</div>
</template>

<script>
export default {
  data () {
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/
      if (regEmail.test(value)) {
        return cb()
      }
      // 返回一个错误提示
      cb(new Error('请输入合法的邮箱'))
    }
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^1[34578]\d{9}$/
      if (regMobile.test(value)) {
        return cb()
      }
      // 返回一个错误提示
      cb(new Error('请输入合法的手机号码'))
    }
    return {
      querInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userformData: [],
      total: 0,
      bjFormVisible: false,
      tjFormVisible: false,
      bianjiForm: {},
      tianjiaForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      ruless: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名在3~10个字符之间',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '用户名在6~15个字符之间',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            validator: checkEmail,
            message: '邮箱格式不正确，请重新输入',
            trigger: 'blur'
          }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          {
            validator: checkMobile,
            message: '手机号码不正确，请重新输入',
            trigger: 'blur'
          }
        ]
      },
      jsForm: {},
      rolesList: [],
      value1: '',
      jsFormVisible: false
    }
  },
  created () {
    const pagesize1 = sessionStorage.getItem('pagesize')
    if (pagesize1) this.querInfo.pagesize = Number(pagesize1)
    this.pagesize = 2
    // console.log(pagesize1)
    this.getuserformData()
  },
  methods: {
    async getuserformData () {
      // const pagenum = sessionStorage.getItem('pagenum')
      // this.querInfo.pagenum = pagenum
      // const pagesize1 = sessionStorage.getItem('pagesize')
      // this.querInfo.pagesize = pagesize1
      const { data: res } = await this.$http.get('users', { params: this.querInfo })
      if (res.meta.status !== 200) return this.$message.error('获取用户数据列表失败')
      this.userformData = res.data.users
      this.total = res.data.total
    //   console.log(res.data)
    },
    handleSizeChange (newSize) {
      this.querInfo.pagesize = newSize
      sessionStorage.setItem('pagesize', newSize)
      this.getuserformData()
      console.log(newSize)
    },
    handleCurrentChange (newPage) {
      this.querInfo.pagenum = newPage
      sessionStorage.setItem('pagenum', newPage)
      this.getuserformData()
      // console.log(newPage)
    },
    async bjForm (id) {
      this.bjFormVisible = true
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) return this.$message.error('获取用户信息错误')
      this.bianjiForm = res.data
    },
    guanbi () {
      this.$refs.editFormRef.resetFields()
      this.bjFormVisible = false
    },
    guanbi1 () {
      this.$refs.editFormRef1.resetFields()
      this.tjFormVisible = false
    },
    xiugaibtn (id) {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请填写完整用户信息')
        const { data: res } = await this.$http.put('users/' + id, { email: this.bianjiForm.email, mobile: this.bianjiForm.mobile })
        if (res.meta.status !== 200) return this.$message.error('获取用户信息失败')
        this.bjFormVisible = false
        this.getuserformData()
        this.$message.success('修改用户信息成功')
      }
      )
    },
    tianjiabtn (id) {
      this.$refs.editFormRef1.validate(async valid => {
        if (!valid) return this.$message.error('请添加完整用户信息')
        const { data: res } = await this.$http.post('users', this.tianjiaForm)
        if (res.meta.status !== 201) return this.$message.error('添加用户信息失败')
        this.tjFormVisible = false
        this.getuserformData()
        this.$message.success('添加用户信息成功')
      }
      )
    },
    async changesj (data) {
      const { data: res } = await this.$http.put(`users/${data.id}/state/${data.mg_state}`)
      if (res.meta.status !== 200) {
        data.mg_state = !data.mg_state
        return this.$message.error('更改用户状态失败')
      }
      this.$message.success('更改用户状态成功')
    },
    delete1 (id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete('users/' + id).then((ret) => {
          if (ret.data.meta.status !== 200) return this.$message.error('删除用户失败')
          this.getuserformData()
        })
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async getjsForm (row) {
      this.jsForm = row
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.rolesList = res.data
      this.jsFormVisible = true
    },
    async jsbtn () {
      const { data: res } = await this.$http.put(`users/${this.jsForm.id}/role`, { rid: this.value1 })
      if (res.meta.status !== 200) return this.$message.error('修改角色失败')
      this.$message.success('修改角色成功')
      this.getuserformData()
      this.jsFormVisible = false
    },
    guanbi2 () {
      this.jsFormVisible = false
    }
  }
}
</script>

<style scoped lang="less">
.btns {
    display: flex;
    align-items: center;
}
</style>
